#pragma once

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include "err.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

using namespace std;
namespace ns_server
{
    using fun_t = std::function<std::string(const std::string &)>;
    static const uint16_t defaultport = 8081;
    static const int backlog = 32;

    class TcpServer;
    struct ThreadData
    {
        int sock;
        string clientip;
        uint16_t clientport;
        TcpServer *current;

        ThreadData(int fd, const string &ip, const uint16_t &port, TcpServer *ts)
            : sock(fd), clientip(ip), clientport(port), current(ts)
        {
        }
    };
    class TcpServer
    {
    private:
        uint16_t port_;
        int listensock_;
        bool quit_;
        fun_t func_;

    public:
        TcpServer(fun_t func, uint16_t port = defaultport) : func_(func), port_(port), quit_(true)
        {
        }
        void initServer()
        {
            listensock_ = socket(AF_INET, SOCK_STREAM, 0);
            if (listensock_ < 0)
            {
                std::cerr << "create socket error" << std::endl;
                exit(SOCKET_ERR);
            }

            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port_);
            local.sin_addr.s_addr = htonl(INADDR_ANY);
            if (bind(listensock_, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                std::cerr << "bind socket error" << std::endl;
                exit(BIND_ERR);
            }
            if (listen(listensock_, backlog) < 0)
            {
                std::cerr << "listensock socket error" << std::endl;
                exit(LISTEN_ERR);
            }
        }
        void start()
        {
            signal(SIGCHLD, SIG_IGN);
            quit_ = false;
            while (!quit_)
            {
                struct sockaddr_in client;
                socklen_t len = sizeof(client);

                int sock = accept(listensock_, (struct sockaddr *)&client, &len);
                if (sock < 0)
                {
                    cerr << "accept error" << endl;
                }

                string clientip = inet_ntoa(client.sin_addr);
                uint16_t clientport = ntohs(client.sin_port);

                std::cout << "获取新连接成功: " << sock << " from " << listensock_ << ", "
                          << clientip << "-" << clientport << std::endl;

                // v1
                // service(sock, clientip, clientport);

                // v2多进程

                // pid_t id = fork();
                // if(id<0)
                // {
                //     close(sock);
                //     continue;
                // }else if(id==0)
                // {
                //     close(listensock_);
                //     //if(fork()>0)exit(0);
                //     service(sock,clientip,clientport);
                //     exit(0);
                // }
                // close(sock);
                // pid_t ret = waitpid(id,nullptr,0);
                // if(ret==id) std::cout << "wait child " << id << " success" << std::endl;

                // v3 多线程
                // pthread_t tid;
                // ThreadData *td = new ThreadData(sock, clientip, clientport, this);
                // pthread_create(&tid, nullptr, ThreadRoutin, td);

                //线程池
                Task t(sock,clientip,clientport,std::bind(&TcpServer::service,this,placeholders::_1,placeholders::_2,placeholders::_3));
                ThreadPool<Task>::getinstance()->pushTask(t);
            }
        }
        static void *ThreadRoutin(void *args)
        {
            pthread_detach(pthread_self());
            ThreadData *td = static_cast<ThreadData *>(args);
            td->current->service(td->sock, td->clientip, td->clientport);
            delete td;
            return nullptr;
        }
        void service(int sock, const string &clientip, const uint16_t &clientport)
        {
            string who = clientip + "-" + to_string(clientport);
            char buffer[1024];

            //ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
            // if (s > 0)
            // {
            //     buffer[s] = 0;
            //     string res = func_(buffer);
            //     cout << who << ">>>" << res << endl;

            //     write(sock, buffer, strlen(buffer));
            // }
            // else if (s == 0)
            // {
            //     cout << who << "quit, me too" << endl;
            // }
            // else
            // {
            //     cerr << "read error" << strerror(errno) << endl;
            // }
            // close(sock);

            while (true)
            {
                ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
                if (s > 0)
                {
                    buffer[s] = 0;
                    string res = func_(buffer);
                    cout << who << ">>>" << res << endl;

                    write(sock,buffer,strlen(buffer));

                }
                else if (s == 0)
                {
                    close(sock);
                    cout << who << "quit, me too" << endl;
                    break;
                }
                else
                {
                    close(sock);
                    cerr << "read error" << strerror(errno) << endl;
                    break;
                }
            }
        }
        ~TcpServer()
        {
        }
    };
}